import { defineStore } from 'pinia';
import { nextTick } from 'vue';
import dayjs from 'dayjs';
import axios from 'axios';
import {
  createTaskApi,
  fetchBgList,
  fetchDigitalList,
  fetchMaterialList,
  fetchTaskDetailApi,
  fetchVoiceList,
  updateTaskInfoApi
} from '@/service/api';
import { router } from '@/router';
import { dataURLToBlob } from '@/utils/common';
import { localStg } from '@/utils/storage';
import { defaultState, getLocalState, removeLocalState, setLocalState } from './store-helper';
import type { State } from './store-helper';
const { VITE_UPLOAD_PATH } = import.meta.env;

export const useStoreKey = 'store';
const useStore = defineStore(useStoreKey, {
  getters: {
    // 获取字典表
    getDict: state => (key: string) => {
      if (!key) return state.dict;
      return (state.dict as any)[key];
    },
    getDigitalId: state => () => {
      return state.digital.id;
    },
    getMaterialId: state => () => {
      return state.material.id;
    },
    getBgId: state => () => {
      return state.bg.id;
    }
  },
  actions: {
    // 侧边栏选项初始化加载
    async init(key?: string) {
      if (key && key === 'bg') {
        const { data: bgList } = await fetchBgList();
        this.$state.dict.bg = bgList || [];
      } else {
        this.$state.dictPromise = Promise.allSettled([
          fetchBgList(),
          fetchDigitalList(),
          fetchMaterialList(),
          fetchVoiceList()
        ]).then(results => {
          const [bg, digital, material, voice] = results.map(v => (v.status === 'fulfilled' ? v.value.data : []));
          // 插入数据，不是赋值
          this.$state.dict.bg = bg.concat(this.$state.uploadFiles);
          this.$state.dict.digital = digital;
          this.$state.dict.material = material;
          this.$state.dict.voice = voice;
        });
      }
    },
    // 编辑时获取信息回显
    async getDraftInfo(id: string) {
      this.$state.isGetDraftData = true;
      console.log('getDraftInfo ==== set true');
      const { data } = await fetchTaskDetailApi(id);
      if (data) {
        console.log('🚀 ~ handleAdd ~ data:', data, JSON.parse(data.content));
        const chacheData = JSON.parse(data.content);
        const sizeData = JSON.parse(data.size);
        // router.push(link);
        // canvas: this.canvas, // 画布内容
        // text: this.text,
        // voice: this.voice,
        // bg: this.bg,
        // digital: this.digital,
        // material: this.material
        this.canvas = chacheData.canvas;
        this.text = chacheData.text;
        this.voice = chacheData.voice;
        this.bg = chacheData.bg;
        this.digital = chacheData.digital;
        this.material = chacheData.material;
        this.canvasConfig.width = sizeData.width;
        this.canvasConfig.height = sizeData.height;
        this.canvasConfig.size = this.getSizeInfoOpiton(sizeData);
      }
      nextTick(() => {
        this.$state.isGetDraftData = false;
        console.log('getDraftInfo ==== set false');
      });
    },
    getSizeInfoOpiton(sizeData: { width: number; height: number }) {
      const { width, height } = sizeData;
      const options = this.$state.dict.canvas;
      const current = options.find((v: any) => v.resolution.width === width && v.resolution.height === height);
      return current.size;
    },
    // 新建时 清空数据
    createTask() {
      this.$state = {
        ...defaultState(),
        dict: this.$state.dict
      };
      this.record();
    },

    checkParams() {
      if (!this.bg.url) {
        window.$message?.error('请选择背景');
        return Promise.reject(new Error('请选择背景'));
      }
      if (!this.digital.url) {
        window.$message?.error('请选择数字人');
        return Promise.reject(new Error('请选择数字人'));
      }
      return Promise.resolve(true);
    },

    // 保存任务  状态-默认0 | 名称 | 分辨率
    // eslint-disable-next-line max-params
    async saveTask({
      status,
      name,
      resolution,
      id,
      playText
    }: {
      status: number;
      name: string;
      resolution: any;
      id?: string;
      playText: string;
    }) {
      if (await this.checkParams()) {
        // videoStatus 0 草稿
        // videoStatus 1 渲染中 导出
        // 任务状态及名称信息
        const creation: any = {
          videoStatus: status || 0,
          videoName: name || '未命名'
        };

        // 预览图
        if (this.cover) creation.coverPicture = this.cover;

        // 任务详情信息
        const creationDetail: any = {
          content: JSON.stringify({
            canvas: this.canvas, // 画布内容
            text: this.text,
            voice: this.voice,
            bg: this.bg,
            digital: this.digital,
            material: this.material,
            contentText: playText,
            size: JSON.stringify({
              width: this.canvasConfig.width,
              height: this.canvasConfig.height
            }),
            resolution
            // uploadFiles: this.uploadFiles // 用户上传文件
          }),
          contentText: playText,
          size: JSON.stringify({
            width: this.canvasConfig.width,
            height: this.canvasConfig.height
          }),
          createTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
        };
        // 分辨率
        if (resolution) creationDetail.resolution = resolution;

        const params: any = {
          creation,
          creationDetail
        };
        params.phone = localStorage.getItem('video-mobile');
        // 编辑
        if (id) {
          params.creation.id = id;
          const { data } = await updateTaskInfoApi(params);
          const link = `${router.currentRoute.value.path}?id=${id}&detailId=${data}&videoName=${name || '未命名'}`;
          router.replace(link);
          return Promise.resolve(id);
        }
        // 新增
        const { data: resData } = await createTaskApi(params);
        const link = `${router.currentRoute.value.path}?id=${resData}&videoName=${name || '未命名'}`;
        router.replace(link);
        return Promise.resolve(resData);
      }
      return Promise.reject(new Error('保存失败'));
    },

    // 更新 && 获取画布封面
    async updateCanvasCover(base64: any, save: boolean) {
      const coverBlob = dataURLToBlob(base64);
      const formData = new FormData();
      formData.append('file', coverBlob, 'cover.png'); // 文件名写死吧
      if (save) {
        const { data: result } = await axios.post(VITE_UPLOAD_PATH, formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
            authorization: `${localStg.get('humanToken')}`
          }
        });
        if (result && result.data) {
          this.cover = result.data.url;
          return Promise.resolve(result.data.url || '');
        }
        return Promise.reject(new Error(`${result.message}`));
      }
      // base64 图片格式展示
      this.cover = base64;
      return Promise.resolve(base64);
    },

    // 更新画布导出内容 => imgs对象集合
    updateCanvasObjects(objects: any) {
      this.canvas = objects;
      this.record();
    },

    // 更新背景选项列表  废弃
    updateBgDictList(url: string) {
      const item = {
        id: Date.now().toString(),
        imageType: 1, // 自定义背景
        url
      };
      // this.$state.uploadFiles.push(item);
      this.$state.dict.bg.unshift(item);
      this.record();
    },

    // 删除背景选项列表
    deleteBgDictItem(id: string | number) {
      // this.$state.uploadFiles = this.$state.uploadFiles.filter((v: any) => v.id !== id);
      this.$state.dict.bg = this.$state.dict.bg.filter((v: any) => v.id !== id);
      this.record();
    },

    // 侧边栏激活状态更新
    updateActiveMenu(index: number) {
      this.activeMenu = index;
      this.record();
    },
    // 当前画布比例尺寸
    updateCanvasSize(size: string) {
      const { resolution, icon, direction } = this.dict.canvas.find((v: any) => v.size === size) || {};
      this.canvasConfig = {
        size,
        icon,
        direction,
        ...resolution
      };
      this.updateFlag = true;
      this.record();
      return Promise.resolve();
    },

    // 选择背景的当前激活tab
    updateBgTab(current: number) {
      this.bgTab = current;
      this.updateFlag = true;
      this.record();
    },

    // 选择数字人
    updateDigital(row: any) {
      this.digital = row;
      console.log(row, 'row========');
      this.updateFlag = true;
      this.record();
    },

    // 选择背景
    updateBg(row: any) {
      const { id, url } = row;
      this.bg.id = id;
      this.bg.url = url;
      this.updateFlag = true;
      this.record();
    },
    // 默认背景
    updateDefault(row: any, type: string) {
      if (type === 'bg') this.defaultBg = row;
      if (type === 'digital') this.defaultDigital = row;
      this.record();
    },

    // 选择道具
    updateMaterial(row: any) {
      const { id, url } = row;
      this.material.id = id;
      this.material.url = url;
      this.updateFlag = true;
      this.record();
    },

    // 选择声音
    updateVoice(voice: any) {
      this.voice = voice;
      this.updateFlag = true;
      this.record();
    },
    async updateVoiceByTimbreId(timbreId: string) {
      await this.dictPromise;
      const voice = this.dict.voice.find((v: any) => v.id === timbreId);
      this.voice = voice;
      this.updateFlag = true;
      this.record();
    },

    // 更新播报文本
    updateText(text: string) {
      this.text = text;
      this.updateFlag = true;
      this.record();
    },

    // 更新状态标识
    toggleUpdateFlag(flag: boolean) {
      this.updateFlag = flag;
      this.record();
    },

    record() {
      // setLocalState(this.$state);
    },
    reset() {
      this.$state = {
        ...defaultState(),
        dict: this.$state.dict
      };
      removeLocalState();
    }
  },
  state: (): State => getLocalState()
});

export { useStore };
